/**
 * <p>Title: liteflow</p>
 * <p>Description: 轻量级的组件式流程框架</p>
 * @author Bryan.Zhang
 * @email weenyc31@163.com
 * @Date 2020/4/1
 */
package io.mft.flow.core;

import cn.hutool.core.util.ReflectUtil;
import io.mft.commons.exception.MFTException;
import io.mft.commons.function.ExecuteReturn;
import io.mft.flow.core.executable.Chain;
import io.mft.flow.core.executable.Executable;
import io.mft.flow.core.executable.ExecutableCache;
import io.mft.flow.core.executable.ExecutableType;
import io.mft.flow.core.executable.Node;
import io.mft.flow.core.executable.component.NodeComponent;
import io.mft.flow.data.ChainContext;

public class FlowExecutor {
	private ExecutableCache executableCache = new ExecutableCache();
	

	public ExecuteReturn execute(String chainId, ChainContext context) throws Exception {
		Executable chain = getExecutable(ExecutableType.CHAIN, chainId);
		if (chain == null) {
			throw new MFTException(-1, "未获取到流程对象[" + chainId + "]");
		}
		// 执行chain
		return chain.execute(context);
	}

	public ExecutableCache getExecutableCache() {
		return executableCache;
	}

	public Executable getExecutable(ExecutableType executableType,String id) {
		return executableCache.getExecutable(executableType,id);
	}

	public <T extends NodeComponent> void addNode(String id, Class<T> nodeComponentClass, String desc,boolean isReload) {
		NodeComponent component = ReflectUtil.newInstance(nodeComponentClass);
		component.setNodeId(id);
		Node node = new Node(id, component);
		executableCache.addExecutable(node,isReload);
	}

	public void addChain(Chain chain,boolean isReload) {
		executableCache.addExecutable(chain,isReload);
	}

}
